/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react'
import PropTypes from 'prop-types';
import { createAlphabetList } from '../../utils/AToZUtil';
import {
	filterMembers,
	modifyList,
	getDataList,
	removeUncheckedItem,
	removeCheckedItem,
	removeCirclarObject
} from '../../utils/ItemsUtil';
import SectionHeader from './SectionHeader';
import MemberCell from './MemberCell';
import store from 'react-native-simple-store';
import SectionItem from './SectionItem';
import HeaderView from './HeaderView';
import MemberList from './MemberList';
import ManagerListView from './ManagerListView';
import ActionSheet from 'react-native-actionsheet';
import * as types from '../../constants/ActionTypes';
import BottomConfirmer from '../../components/BottomConfirmer';
import ToastUtil from '../../utils/ToastUtil';
const _ = require('lodash');
import LoadingSpinnerOverlay from '../../components/LoadingSpinnerOverlay';
import EditTeam from '../../components/team/EditTeam';

import {
	DeviceEventEmitter,
	InteractionManager,
	ListView,
	StyleSheet,
	ScrollView,
	View,
	Dimensions,
	Text
} from 'react-native';


const propTypes = {}

const CANCEL_INDEX = 0
const DESTRUCTIVE_INDEX = 5
const options = [ '取消', '添加主管', '添加成员', '删除成员', '修改名称']
const title = '团队管理'

const alphabetListPaddingTop = 130;

class TeamProfile extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			managerDataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2
			}),
			selected: '',
			searchValue: null,
			team: null,
			enableMemberDeletion: false,
			enableManagerDeletion: false,
			key: null,
			editTeamVisible: false,
			showAddDialog: false,
			teamName: ''
		}

		this.team = this.props.navigation.state.params.team;
		this.renderManagerListView = this.renderManagerListView.bind(this);
		this.renderMemberCell = this.renderMemberCell.bind(this);
		this.onChange = this.onChange.bind(this);
		this.handlePress = this.handlePress.bind(this)
    this.showActionSheet = this.showActionSheet.bind(this);
		this.onNavButtonPress = this.onNavButtonPress.bind(this);
		this.renderManagerCell = this.renderManagerCell.bind(this)
		this.onMemberItemChecked = this.onMemberItemChecked.bind(this)
		this.onManagerItemChecked = this.onManagerItemChecked.bind(this)
		this.onDeleteConfirm = this.onDeleteConfirm.bind(this)
		this.onCancel = this.onCancel.bind(this)
		this.onSaveTeamSave = this.onSaveTeamSave.bind(this)
		this.onSaveTeamCancel = this.onSaveTeamCancel.bind(this)
	};

	componentDidMount () {
		this.unmounted = false
		this.props.navigation.setParams({ handleCheck: this.onNavButtonPress });
		InteractionManager.runAfterInteractions(() => {
			const { team } = this.props.navigation.state.params;
			this.setState({teamName: team.team_name})
			this.updateState(team, null)
		});
	};

	componentWillReceiveProps(nextProps) {
		const { member, teamActions } = nextProps;
		const teamState = nextProps.team
		const { team } = this.props.navigation.state.params;

		requestAnimationFrame(() => {
			if(team.type === types.START_SAVE_TEAM) {
				this._modalLoadingSpinnerOverLay.show()
			} else if(teamState.type === types.RESPONSE_SAVE_TEAM 
				&& teamState && teamState.editingTeam.id === team.id) {
					const callback = teamState.callback ? JSON.parse(teamState.callback) : {}
					this._isResetTeamState = true;
					this._modalLoadingSpinnerOverLay.hide()
					requestAnimationFrame(() => {
						if (callback.errcode === 0) {
							this.updateState(teamState.editingTeam, null, {enableMemberDeletion: false, enableManagerDeletion: false})
						} else {
							this.updateState(this.teamCopy)
						}
					})
			}
		})
	}

	onCancel () {
		this.setState({
			enableManagerDeletion: false,
			enableMemberDeletion: false
		})
	}

	componentWillUnmount () {
		if (this._isResetTeamState === true) {
			const { teamActions } = this.props;
			teamActions.emptyTeamList([], true)
		}
	}
	
  onNavButtonPress () {
    this.showActionSheet()
	};

	renderManagerCell (item) {
		return (
			<MemberCell
			checkbox={this.state.enableManagerDeletion}
			showImage={true}
			item={item}
			rightText='主管'
			onChecked={this.onManagerItemChecked}
			cellContainerStyle={styles.cellContainerStyle} />
		)
	};

	modifyMemberCheckedItem (members, checkedItem) {
		let refresh = getDataList(members);
		// window.console.log(checkedItem.checked === undefined || !checkedItem.checked,
		// 	JSON.stringify(checkedItem), members, checkedItem.checked, 'modifyMemberCheckedItem')
		return modifyList(refresh, ['suid', checkedItem.suid], 'checked',
				checkedItem.checked === undefined || !checkedItem.checked, false, true
		)
	}

	onManagerItemChecked (item) {
		const { team } = this.state
		if (team) {
			const { team_managers } = team;
			team.team_managers = this.modifyMemberCheckedItem(team_managers, item)
			requestAnimationFrame(() => this.updateState(team))
		}
	}

	onMemberItemChecked (item) {
		const { team } = this.state
		if (team) {
			const { team_members } = team;
			team.team_members = this.modifyMemberCheckedItem(team_members, item)
			requestAnimationFrame(() => this.updateState(team))
		}
	}

	onDeleteConfirm () {
		const { team } = this.state
		this.teamCopy = _.clone(team)
		const leftManagers = removeCheckedItem(getDataList(team.team_managers));
		const leftMemebers = removeCheckedItem(getDataList(team.team_members));
		if (leftManagers.length === 0) {
			return ToastUtil.showShort('不能取消最后一个管理员!');
		}
		team.team_managers = leftManagers
		team.team_members = leftMemebers

		const { user } = this.props.user;
		const { teamActions } = this.props;
		
		teamActions.requestSaveTeam(removeCirclarObject(team), user.siteId, user.token)
	}

	onChange (ev) {
		const { team } = this.props.navigation.state.params;
		const match = ev.nativeEvent.text;
		// console.log(match, 'match')
		if (match) {
			let managers = filterMembers(team.team_managers, 'name', match);
			const freshTeam = Object.assign(managers, {team_managers: managers})
			this.updateState(freshTeam, match);
		} else {
			// console.log('team.team_managers', team)
			this.updateState(team);
		}
	};

	handlePress(i) {
		if (i === 4) {
			this.setState({showAddDialog: true})
		} if (i === 3) {
			this.deleteMembers()
		} else if (i === 2) {
			this.navToMember(false);
		} else if (i === 1){
			this.navToMember(true);
		}
    this.setState({
      selected: i
		})
	}

	deleteMembers () {
		requestAnimationFrame(() => this.setState({
			enableManagerDeletion: true, 
			enableMemberDeletion: true, 
			key: Math.random() 
		}))
	};

	navToMember (isManager) {
		const { teamActions } = this.props
		requestAnimationFrame(() => {
			const { navigate } = this.props.navigation;
			const { team } = this.props.navigation.state.params;
			teamActions.resetTeamType();
			navigate('MemberChose', {isManager, team, title: isManager ? '添加主管' : '添加成员'});
		});
	}

	clearTimer = (timer) => {
		cancelAnimationFrame(timer);
		this.setState({timer: false})
	}

	updateState (team, match, states) {
		if (this.unmounted) {
			this.unmounted = false;
			return
		}
		const managerDataSource = this.state.managerDataSource.cloneWithRows(getDataList(team.team_managers));
		this.setState(Object.assign({
			managerDataSource: managerDataSource,
			team: team
		}, states || {}));
	};

	renderMemberCell (section) {
		return (
			<MemberCell
			checkbox={this.state.enableMemberDeletion}
			showImage={true}
			item={section.item}
			onChecked={this.onMemberItemChecked}
			rightText='成员' />
		)
	}

	renderManagerListView () {
		const props = Object.assign({}, {
			isRefreshing: false,
			dataSource: this.state.managerDataSource,
			style: styles.ManagerListStyle,
			renderRow: this.renderManagerCell
		}, this.props)

		return (
			<ManagerListView
			{...props}
			/>
		)
	};

	showActionSheet() {
    this.ActionSheet.show()
	}

	onSaveTeamSave (teamName) {
		this.setState({showAddDialog: false, team_name: teamName})
		const { team } = this.props
		team.team_name = teamName
		console.log(teamName, 'teamName')
		this.props.navigation.setParams({team: team})
  }

  onSaveTeamCancel() {
    this.setState({showAddDialog: false})
  }

  renderEditTeam = () => {
    if (this.state.showAddDialog) {
			return (<EditTeam {...this.props}
				teamName={this.state.teamName}
				titleText={'编辑团队名称'}
				visible={this.state.editTeamVisible} 
				onSave={this.onSaveTeamSave}
				teamId={this.team.id}
				teamActions={this.props.teamActions}
				onCancel={this.onSaveTeamCancel}
      />)
    }
  };

	renderActionSheet () {
		return (
      <ActionSheet
			ref={o => this.ActionSheet = o}
			title={title}
			options={options}
			cancelButtonIndex={CANCEL_INDEX}
			destructiveButtonIndex={DESTRUCTIVE_INDEX}
			onPress={this.handlePress}
			/>
    )
	};

	render() {
		return  (
			<View style={styles.containerStyle}>
				{this.renderEditTeam()}
				{ this.state.team &&
					<MemberList
					enableManagerDeletion={this.state.enableManagerDeletion}
					enableMemberDeletion={this.state.enableMemberDeletion}
					key={this.state.key}
					renderHeaderContentRow = {this.renderManagerCell}
					memberList = {this.state.team.team_members}
					cell={this.renderMemberCell}
					renderHeaderContent = {this.renderManagerListView}
					onChange= {this.onChange}
					/>
				}
				{this.renderActionSheet()}
				{ this.state.enableMemberDeletion &&
					<BottomConfirmer
					confirmText='删除'
					onCancel={this.onCancel} 
					onConfirm={this.onDeleteConfirm}
					containerStyle={styles.bottomConfirmerStyle}
					/>
				}
				{
					<LoadingSpinnerOverlay
					ref={ component => this._modalLoadingSpinnerOverLay = component }/>
				}
				</View>
		)
  }
}

const styles = StyleSheet.create({
	containerStyle: {
		flex: 1
	},
	contentWrapperStyle : {
		height: 100
	},
	ManagerListStyle: {
	},
	bottomConfirmerStyle: {
	}
});

TeamProfile.propTypes = propTypes;

export default TeamProfile;
